package com.material.vtool.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.URL;
import java.util.List;

public class EhcacheUtil {

    private static final Logger logger = LogManager.getLogger(com.material.vtool.utils.EhcacheUtil.class);

    private CacheManager cacheManager;

    private static com.material.vtool.utils.EhcacheUtil ehCache;

    public EhcacheUtil() {
        initCache();
    }

    public EhcacheUtil(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    public void initCache() {
        URL url = getClass().getResource("/ehcache.xml");
        cacheManager = CacheManager.create(url);
    }

    public CacheManager getCacheHandler() {
        return cacheManager;
    }

    public void stopCache() {
        cacheManager.shutdown();
    }

    public void put(String cacheName, String key, Object value) {
        Cache cache = cacheManager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    public Object get(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
        return cacheManager.getCache(cacheName);
    }

    public String[] getCacheName() {
        return cacheManager.getCacheNames();
    }

    public void remove(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        cache.remove(key);
    }

    public void removeAll() {
        String[] StringList = this.getCacheName();

        for (String string : StringList) {
            Cache cache = cacheManager.getCache(string);
            List list = cache.getKeys();
            cache.removeAll(list);
        }
    }

    public void removeCacheNameAll(String cacheName) {
        logger.info("[startRemoveCacheByName] = " + cacheName);
        Cache cache = cacheManager.getCache(cacheName);
        List list = cache.getKeys();
        cache.removeAll(list);
        logger.info("[endRemoveCacheByName] = " + cacheName);
    }

    public static com.material.vtool.utils.EhcacheUtil getInstance() {
        if (ehCache == null) {
            ehCache = new com.material.vtool.utils.EhcacheUtil();
        }
        return ehCache;
    }

    public static void main(String[] args) {
        String[]  string = com.material.vtool.utils.EhcacheUtil.getInstance().getCacheName();
        for (String name : string) {
//    		list.addAll(EhCacheHelper.getInstance().get(name).getKeys());
            List<String> keys = com.material.vtool.utils.EhcacheUtil.getInstance().get(name).getKeys();
            keys.stream().forEach(s -> System.out.println(s));
        }
    }

}
